﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LitJson;
using SufeiUtil;

namespace Live
{
    public class ZhanQiTv : BasePlatform
    {
        private readonly ZhanQiTvRoom room = new ZhanQiTvRoom();

        public override bool Init(string url)
        {
            //https://www.zhanqi.tv/xiong520
            string[] urlPattern = url.Split(new char[] {'/'});
            if (urlPattern.Length < 4)
            {
                return false;
            }
            //房间Id
            string roomId = urlPattern[3];
            room.ID = roomId;

            string html = ReqRoomInfo(room.ID);

            JsonData data = JsonMapper.ToObject(html);
            int errcode = int.Parse(data["code"].ToString());
            if (errcode != 0)
            {
                return false;
            }

            room.UserId = data["data"]["uid"].ToString();
            room.UserName = data["data"]["nickname"].ToString();
            room.UserAvatar = data["data"]["avatar"].ToString();
            room.Name = data["data"]["title"].ToString();
            room.Status = data["data"]["status"].ToString();
            room.VideoId = data["data"]["videoId"].ToString();
            room.LiveUrl = ReqLiveUrl(room.VideoId);

            return true;
        }

        private string ReqLiveUrl(string videoId)
        {
            videoId = videoId.Replace("\r\n", "");

            string url = String.Format("http://wshdl.load.cdn.zhanqi.tv/zqlive/{0}.flv?get_url=1", videoId);

            return "http://dlhls.cdn.zhanqi.tv/zqlive/" + videoId + ".m3u8";
        }

        protected override string ReqRoomInfo(string roomId)
        {
            string url = String.Format("https://www.zhanqi.tv/api/static/v2.1/room/domain/{0}.json", roomId);

            HttpItem item = new HttpItem();
            item.Method = "GET";
            item.URL = url;
            item.Host = "www.zhanqi.tv";
            item.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            item.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";

            return mHelper.GetHtml(item).Html;
        }


        public override bool IsLive()
        {
            return room.Status.Equals("4");
        }

        public override Room GetRoomInfo()
        {
            return room;
        }

        public override string GetLivePlayUrl()
        {
            return room.LiveUrl;
        }
    }
}